package com.lingxu.api.utils;

import lombok.extern.log4j.Log4j2;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName DbMetadataUtil
 * @Description 描述
 * @Author junyi.wang
 * @Date 2025/7/21 17:07
 */
@Log4j2
public class DbMetadataUtil {
    public static Map<String, Integer> getColumnLengths(DataSource dataSource, String tableName) {
        Map<String, Integer> columnLengths = new HashMap<>();
        try (Connection conn = dataSource.getConnection()) {
            DatabaseMetaData metaData = conn.getMetaData();
            ResultSet columns = metaData.getColumns(null, null, tableName, null);
            while (columns.next()) {
                String columnName = columns.getString("COLUMN_NAME").toLowerCase();
                int columnSize = columns.getInt("COLUMN_SIZE");
                columnLengths.put(columnName, columnSize);
            }
        } catch (SQLException e) {
            log.error("获取表结构失败", e);
        }
        return columnLengths;
    }
}
